package cn.life.common.push.ios;

import cn.life.common.entity.vo.PushVo;
import cn.life.common.push.hw.HwPushConfig;
import javapns.devices.Device;
import javapns.devices.implementations.basic.BasicDevice;
import javapns.notification.AppleNotificationServerBasicImpl;
import javapns.notification.PushNotificationManager;
import javapns.notification.PushNotificationPayload;
import javapns.notification.PushedNotification;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 *
 * @Author 李佳明
 * @Date 2018-09-06 14:36
 */
@Configuration
@PropertySource({"classpath:config.properties"})
public class IosPush {

    @Autowired
    private Environment env;

    /**
     * ios推送方法
     * @throws Exception
     */
    public void iosPush(PushVo pushVo) throws Exception{

        //1.赋值
        String title = pushVo.getTitle();
        JSONObject args = pushVo.getExtra();
        Integer messageType = pushVo.getMessageType();
        List<String> tokenList = pushVo.getUserList();
        int count = pushVo.getCount();

        //2.获取配置信息

        //获取Bean信息
        WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
        IosPushConfig iosPushConfig = (IosPushConfig) wac.getBean("iosPushConfig");

        String p12Path = iosPushConfig.getP12Path();
        String p12Pwd = iosPushConfig.getP12Pwd();
        boolean p12Formal = iosPushConfig.getP12Formal();

        try {
            JSONObject obj=new JSONObject();
            JSONObject aps=new JSONObject();
            aps.put("alert", title);
            aps.put("badge", count);
            aps.put("sound", "shake_sound_male.wav");
            aps.put("content-available", 1);
            obj.put("aps", aps);
            if(args==null){
                obj.put("args", "");
            }else{
                obj.put("args", args);
            }
            PushNotificationPayload payLoad= PushNotificationPayload.fromJSON(obj.toString());
            PushNotificationManager pushManager = new PushNotificationManager();
            pushManager.initializeConnection(new AppleNotificationServerBasicImpl(p12Path, p12Pwd, p12Formal));
            List<PushedNotification> notifications = new ArrayList<PushedNotification>();
            // 推送方式,单挑推送or群体推送
            if (tokenList.size()==1) {
                Device device = new BasicDevice();
                device.setToken(tokenList.get(0));
                PushedNotification notification = pushManager.sendNotification(device, payLoad, true);
                notifications.add(notification);
            } else {
                List<Device> device = new ArrayList<Device>();
                for (String token : tokenList) {
                    device.add(new BasicDevice(token));
                }
                notifications = pushManager.sendNotifications(payLoad, device);
            }
            List<PushedNotification> failedNotifications = PushedNotification.findFailedNotifications(notifications);
            List<PushedNotification> successfulNotifications =
                    PushedNotification.findSuccessfulNotifications(notifications);
            int failed = failedNotifications.size();
            int successful = successfulNotifications.size();
            if (successful > 0 && failed == 0) {
                System.out.println("-----All notifications pushed success (" + successfulNotifications.size() + "):");
            } else if (successful == 0 && failed > 0) {
                System.out.println("-----All notifications pushed failed(" + failedNotifications.size() + "):");
                System.out.println(""+failedNotifications.toString());
            }else if (successful == 0 && failed == 0) {
                System.out.println("No notifications could be sent, probably because of a critical error");
            }else {
                System.out.println("------Some notifications pushed failed (" + failedNotifications.size() + "):");
                System.out.println("------Others pushed success(" + successfulNotifications.size() + "):");
            }
            pushManager.stopConnection();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("push faild!");
            return;
        }
    }
}
